package jcataloger.gui;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.text.Element;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.ImageView;

/**
 * JEditorPane does not support reading relative images in a html document. This class <br>
 * fixes it.
 * @author sekobey
 *
 */
public class FixedHTMLEditorKit extends HTMLEditorKit {
	public ViewFactory getViewFactory() {
		if (defaultFactory == null) {
			defaultFactory = new FixedHTMLFactory(super.getViewFactory());
		}
		return defaultFactory;
	}

	private static class FixedHTMLFactory implements ViewFactory {
		public FixedHTMLFactory(ViewFactory factory) {
			oldFactory = factory;
		}
		public View create(Element elem) {
			View result;
			result = oldFactory.create(elem);
			if (result instanceof ImageView) {
				String src = (String)elem.getAttributes().
								getAttribute(HTML.Attribute.SRC);
				result = new NewImageView(elem, src);
			}
			return result;
		}
		private static class NewImageView extends ImageView {
			String source;
			public NewImageView(Element elem, String src) {
				super(elem);
				source = src;
			}
			public Image getImage() {
				Image img = null;
				try {
					//return image
					URL url = getClass().getClassLoader().getResource(source);
					if ( url == null ) {
						url = getClass().getClassLoader().getResource("javax/swing/text/html/icons/image-delayed.gif");
					}
					img = Toolkit.getDefaultToolkit().getImage(url);
					//forcing image to load synchronously
					ImageIcon ii = new ImageIcon();
					ii.setImage(img);
				} catch (Exception e) {
					
				}
				
				return img;
			}
			public URL getImageURL() {
				// here we return url to some image. It might be any
				// existing image.  we need to move ImageView to the
				// state where it thinks that image was loaded.
				// ImageView is calling getImage to get image for
				// measurement and painting when image was loaded
				return getClass().getClassLoader().
				getResource("javax/swing/text/html/icons/image-delayed.gif");
			}
		}

		private ViewFactory oldFactory;
	}
	private static ViewFactory defaultFactory = null;
}